package com.cloudcc.mobile.im.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.bus.MessageNumX;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrDefaultHandler;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrFrameLayout;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrHandler;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.dao.impl.ApprovalEngineImpl;
import com.cloudcc.mobile.entity.CoworkerEntity;
import com.cloudcc.mobile.event.CoworkerEventList.CoworkerListEvent;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.presenter.ContactsPresenter;
import com.cloudcc.mobile.util.CharacterParser;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.util.UserUtils;
import com.cloudcc.mobile.view.activity.Myinformation;
import com.cloudcc.mobile.view.activity.UserInfoActivity;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.view.fragment.MenuRightFragment;
import com.cloudcc.mobile.view.mymodel.cowerentity;
import com.cloudcc.mobile.weight.ClearEditText;
import com.cloudcc.mobile.weight.SideBar;
import com.cloudcc.mobile.weight.SideBar.OnTouchingLetterChangedListener;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.litesuits.android.log.Log;
import com.mypage.utils.SaveTemporaryData;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import butterknife.Bind;

/**
 * 关注同事
 * 
 * @author lhy
 * @date 2015/12/08/12:00
 */
public class GuanzhuActivity extends BaseActivity implements OnClickListener,
		ExpandableListView.OnChildClickListener,
		ExpandableListView.OnGroupClickListener, PtrHandler, IEventLife {
	private ApprovalEngineImpl engine = new ApprovalEngineImpl();
	protected CharacterParser characterParser;
	private SlidingMenu menu_R;
	// @Bind(R.id.new_load_more_list_view_ptr_frame)
	// protected PtrFrameLayout mRefreshLayout;
	// @Bind(R.id.new_load_more_list_view_container)
	// protected LoadMoreListViewContainer mLoadMoreLayout;
	@Bind(R.id.new_filter_edit)
	protected ClearEditText mClearEditText;
	//
	// @Bind(R.id.headerbar)
	// protected CloudCCTitleBar headerbar;

	// @Bind(R.id.bar_title_text)
	// TextView title;

	@Bind(R.id.newcoworexpandablelist)
	ExpandableListView expandablelist;
	@Bind(R.id.cower_sidrbar)
	SideBar sideBar;
	@Bind(R.id.backcowor)
	ImageView backcowor;
	@Bind(R.id.sousuo_hint)
	TextView sousuo_hint;
	@Bind(R.id.message_right)
	ImageView message_right;
	@Bind(R.id.message_num_tz)
	TextView message_num_tz;
	@Bind(R.id.message_num_99)
	TextView message_num_99;
	protected int[] colors;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		String[] array = mContext.getResources().getStringArray(
				R.array.logo_colors);
		colors = new int[array.length];
		for (int i = 0; i < array.length; i++) {
			colors[i] = Color.parseColor(array[i]);
		}
		// initRefresh()
		initMenu();
		initclick();
		requestData();
		addListener();
		initFilter();
	}
	public void onEventMainThread(MessageNumX event) {

		message_num_tz.setText(event.messageNumX+"");
		if(event.messageNumX>0) {
			message_num_tz.setVisibility(View.VISIBLE);
			if(event.messageNumX>99) {
				message_num_tz.setVisibility(View.INVISIBLE);
				message_num_99.setVisibility(View.VISIBLE);
			}

		}else {
			message_num_tz.setVisibility(View.INVISIBLE);
			message_num_99.setVisibility(View.INVISIBLE);
		}

	}
	private void MessageSetNCL(){
		long messagenum = 0;
		messagenum= RunTimeManager.getInstance().getMessageNx();
		message_num_tz.setText(messagenum+"");

		if(messagenum>0) {
			message_num_tz.setVisibility(View.VISIBLE);
			if(messagenum>99) {
				message_num_tz.setVisibility(View.INVISIBLE);
				message_num_99.setVisibility(View.VISIBLE);
			}

		}else {
			message_num_tz.setVisibility(View.INVISIBLE);
			message_num_99.setVisibility(View.INVISIBLE);
		}

	}
	private void initclick() {
		message_right.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				menu_R.showMenu();
			}
		});
	}
	private void initMenu() {
		Fragment leftMenuFragment = new MenuRightFragment();
		getSupportFragmentManager().beginTransaction()
				.replace(R.id.id_Right_menu_frame, leftMenuFragment).commit();
		menu_R = new SlidingMenu(this);
		menu_R.setMode(SlidingMenu.RIGHT);
		menu_R.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE); // 触摸边界拖出菜单
		menu_R.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		menu_R.setOffsetFadeDegree(0.4f);
		menu_R.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
		View viewRi = LayoutInflater.from(this).inflate(R.layout.right_menu_id,
				null);
		menu_R.setMenu(viewRi);
	}
	private void initFilter() {
		characterParser = CharacterParser.getInstance();
		// 根据输入框输入值的改变来过滤搜索
		mClearEditText.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
				filterData(s.toString());
				if (mClearEditText.length() > 0) {
					sousuo_hint.setVisibility(View.GONE);
				} else {
					sousuo_hint.setVisibility(View.VISIBLE);

				}

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

	}

	/**
	 * 根据输入框中的值来过滤数据并更新ListView
	 * 
	 * @param filterStr
	 */
	private void filterData(String filterStr) {
		List<CoworkerEntity> filterDateList = new ArrayList<CoworkerEntity>();
		List<String> datagroup = new ArrayList<String>();
		Map<String, List<CoworkerEntity>> childmap = new HashMap<String, List<CoworkerEntity>>();
		if (TextUtils.isEmpty(filterStr)) {
			datagroup.addAll(datagroupnew);
			childmap.putAll(childmapnew);
		} else {
			datagroup.clear();
			childmap.clear();
			filterDateList.clear();
			String key = null;
			Log.d("initfileye", "遍历的数据" + childmapnew.size());
			for (Entry<String, List<CoworkerEntity>> entry : childmapnew
					.entrySet()) {
				List<CoworkerEntity> value = entry.getValue();
				for (int i = 0; i < value.size(); i++) {

					String name = value.get(i).getName();
					if (name != null
							&& (name.indexOf(filterStr.toString().toLowerCase()) != -1 || characterParser
									.getSelling(name).startsWith(
											filterStr.toString().toLowerCase()))) {
						key = entry.getKey();
						filterDateList.add(value.get(i));
						Log.d("initfileye", "添加的数据" + value.get(i).getName() + ":::"
								+ key);

					}
				}
				if (key != null && filterDateList != null) {
					for (int i = 0; i < filterDateList.size(); i++) {
						Log.d("initfileye", "展示的数据"
								+ filterDateList.get(i).getName() + "::" + key);
					}
					//为了防止重复新增的list
					List<CoworkerEntity> filterDateListnew = new ArrayList<CoworkerEntity>();
					filterDateListnew.addAll(filterDateList);
					datagroup.add(key);
					childmap.put(key, filterDateListnew);
					Log.d("initfileye", "走了几波按摩" + key + "11111111111");
					key = null;
					filterDateList.clear();
				}

			}
		}
		Log.d("initfileye",
				"最后的数据::" + childmapnew.size() + "::" + datagroup.size() + "::"
						+ childmap.size());
		if (adapter != null) {
			// onRequestFinish(ListUtils.isEmpty(filterDateList));
			adapter.changeData(datagroup, childmap);
		}
	}

	private void addListener() {
		backcowor.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				GuanzhuActivity.this.finish();
				
			}
		});
		// 设置右侧触摸监听
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {
			@SuppressLint("NewApi")
			@Override
			public void onTouchingLetterChanged(String s) {
				try {
					int a = -1;
					for (int i = 0; i < listnewgroup.size(); i++) {
						if (s.equals(listnewgroup.get(i))) {
							a = i;
						}
					}
					if (a != -1) {
						expandablelist.setSelectedGroup(a);
					}

				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		});

	}

	protected List<CoworkerEntity> mContactes = new ArrayList<CoworkerEntity>();

	protected ContactsPresenter mContactPresenter = new ContactsPresenter();
	List<cowerentity> cowerentitylist;
	String aa;
	List<String> list = new ArrayList<String>();// 计划是group
	List<String> listnewgroup = null;
	List<List<cowerentity>> listshuju = new ArrayList<List<cowerentity>>();
	Map<String, List<CoworkerEntity>> map = new HashMap<String, List<CoworkerEntity>>();
	int tag = 0;

	public void requestData() {
		mContactPresenter.getSubStaffListGZ();

	}
	public void onEventMainThread(CoworkerListEvent event) {
		// headerbar.completeProgress();
		// mRefreshLayout.refreshComplete();
		if (event.isError()) {
			Toast.makeText(mContext, event.getMessage(), 0).show();
			return;
		}
		try {
			Log.d("shujushishashend", event.getData().get(0).getPinyin()
					.substring(0, 1));
			listnewgroup = new ArrayList<String>();
			for (int i = 0; i < event.getData().size(); i++) {
				listnewgroup.add(event.getData().get(i).getPinyin()
						.substring(0, 1));
			}
			removeDuplicateWithOrder(listnewgroup);
			List<CoworkerEntity> list;
			//排序
			try {
				Collections.sort(listnewgroup);
			} catch (Exception e) {
				// TODO: handle exception
			}
			for (int i = 0; i < listnewgroup.size(); i++) {
				list = new ArrayList<CoworkerEntity>();
				for (int j = 0; j < event.getData().size(); j++) {
					if (listnewgroup.get(i).equals(
							event.getData().get(j).getPinyin().substring(0, 1))) {
						list.add(event.getData().get(j));
					}
				}
				map.put(listnewgroup.get(i), list);
			}
//			 for (Entry<String, List<CoworkerEntity>> entry : map.entrySet()) {
//				   
//				    Log.d("bianlimap", "建"+entry.getKey()+"值"+entry.getValue().get(0).getName());
//				          }
			adapter = new MyexpandableListAdapter(mContext);
			expandablelist.setAdapter(adapter);
			int groupCount = expandablelist.getCount();
			for (int i = 0; i < groupCount; i++) {
				expandablelist.expandGroup(i);
			}
			;
			adapter.notifyDataSetChanged();
			expandablelist.expandGroup(tag);
			tag++;
			Log.d("initfileye",
					"获取数据前" + map.size() + "::" + childmapnew.size());
			// 赋值
			datagroupnew.addAll(listnewgroup);
			childmapnew.putAll(map);
			Log.d("initfileye", "获取数据" + map.size() + "::" + childmapnew.size());
		} catch (Exception e) {
		}

		// refreshData(event.getData());
	}

	public static void removeDuplicateWithOrder(List list) {
		Set set = new HashSet();
		List newList = new ArrayList();
		for (Iterator iter = list.iterator(); iter.hasNext();) {
			Object element = iter.next();
			if (set.add(element))
				newList.add(element);
		}
		list.clear();
		list.addAll(newList);
	}

	// 刷新后使用这个保存之前的总数据。不能使用之前的 会覆盖
	List<String> datagroupnew = new ArrayList<String>();
	Map<String, List<CoworkerEntity>> childmapnew = new HashMap<String, List<CoworkerEntity>>();
	public MyexpandableListAdapter adapter;

	@Override
	public boolean onGroupClick(ExpandableListView parent, View v,
			int groupPosition, long id) {
		return false;
	}

	@Override
	public boolean onChildClick(ExpandableListView parent, View v,
			int groupPosition, int childPosition, long id) {

		return false;
	}

	@Override
	public void onClick(View v) {

	}

	@Override
	public int getLayoutId() {
		return R.layout.newguanzhu;
	}

	@Override
	public boolean checkCanDoRefresh(PtrFrameLayout frame, View content,
			View header) {
		return PtrDefaultHandler.checkContentCanBePulledDown(frame,
				expandablelist, header);
	}

	class MyexpandableListAdapter extends BaseExpandableListAdapter {
		private Context context;
		private LayoutInflater inflater;

		// private Button loadMore;

		public MyexpandableListAdapter(Context context) {
			this.context = context;
			inflater = LayoutInflater.from(context);

		}

		public void changeData(List<String> datagroup,
				Map<String, List<CoworkerEntity>> childmap) {
			if (listnewgroup != null) {
				listnewgroup.clear();
				// listnewgroup = null;
			}
			if (map != null) {
				map.clear();
				// map=null;
			}
			Log.d("initfileye", "最后的数据222::" + childmapnew.size() + "::"
					+ datagroup.size() + "::" + childmap.size());

			listnewgroup.addAll(datagroup);
			map.putAll(childmap);
			Log.d("isnull", "is:" + listnewgroup != null + "::" + (map != null));

			notifyDataSetChanged();
			for (int i = 0; i < listnewgroup.size(); i++) {
				expandablelist.expandGroup(i);
			}
			;
		}

		@Override
		public int getGroupCount() {
			return listnewgroup.size();
		}

		@Override
		public int getChildrenCount(int groupPosition) {

			return map.get(listnewgroup.get(groupPosition)).size();

		}

		@Override
		public Object getGroup(int groupPosition) {
			return listnewgroup.get(groupPosition);
		}

		@Override
		public Object getChild(int groupPosition, int childPosition) {
			return map.get(listnewgroup.get(groupPosition)).get(childPosition);
		}

		@Override
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		@Override
		public boolean hasStableIds() {
			return true;
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			GroupHolder groupHolder = null;
			groupHolder = new GroupHolder();
			convertView = inflater.inflate(R.layout.cower_group, null);
			groupHolder.textView = (TextView) convertView
					.findViewById(R.id.cower_group_text);
			LinearLayout layoutBtn = (LinearLayout) convertView
					.findViewById(R.id.layoutBtn);
			layoutBtn.setVisibility(View.GONE);
			groupHolder.textView.setText(listnewgroup.get(groupPosition));
			convertView.setTag(groupHolder);
			
			
			
			

			return convertView;
		}

		@Override
		public View getChildView(final int groupPosition,
				final int childPosition, boolean isLastChild, View convertView,
				ViewGroup parent) {
			childHolder holder;
			holder = new childHolder();
			convertView = inflater.inflate(R.layout.cower_item,parent, false);
			holder.textView = (TextView) convertView
					.findViewById(R.id.cower_item_text);
			holder.image = (ImageView) convertView
					.findViewById(R.id.cower_image);
			holder.ll = (LinearLayout) convertView.findViewById(R.id.childll);
			if (isLastChild) {
				holder.line = convertView.findViewById(R.id.cower_item_line);
				holder.line.setVisibility(View.GONE);
			}
			holder.ll.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
//					Intent intent = new Intent(GuanzhuActivity.this,
//							NewUserInfoActivity.class);
//					intent.putExtra(
//							UserInfoActivity.KEY_USERID,
//							map.get(listnewgroup.get(groupPosition))
//									.get(childPosition).getId());
//					mContext.startActivity(intent);


					SaveTemporaryData.mSmart="";
					SaveTemporaryData.detailDyamic = "";
					SaveTemporaryData.GeneralOne = true;
					Intent intent = new Intent(mContext,
							Myinformation.class);
					if (RunTimeManager.getInstance().getUserId().equals(map.get(listnewgroup.get(groupPosition))
							.get(childPosition).getId())) {
						intent.putExtra("isme", "cowme");
					}
					intent.putExtra(
							UserInfoActivity.KEY_USERID,
							map.get(listnewgroup.get(groupPosition))
									.get(childPosition).getId());
					intent.putExtra(
							"name",
							map.get(listnewgroup.get(groupPosition))
									.get(childPosition).getName());
					mContext.startActivity(intent);

				}
			});
			holder.textView.setText(map.get(listnewgroup.get(groupPosition))
					.get(childPosition).getName());
			String uri = UrlTools.getTopImage(map
					.get(listnewgroup.get(groupPosition)).get(childPosition)
					.getId());
			int colorindex = childPosition % colors.length;
			UserUtils.setLogoRound_z(uri, holder.image, colors[colorindex],
					getNickRowName(map.get(listnewgroup.get(groupPosition))
							.get(childPosition).getName()), mContext);

			return convertView;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return false;
		}

	}

	class GroupHolder {
		TextView textView;
	}

	class childHolder {
		TextView textView;
		ImageView image;
		LinearLayout ll;
		View line;
		// Button loadMore;
	}

	@Override
	public void register() {
		EventEngine.register(this);
	}

	@Override
	public void unRegister() {
		EventEngine.uregister(this);
	}

	@Override
	public void onResume() {
		super.onResume();
		MessageSetNCL();
		requestData();
		register();
	}

	@Override
	public void onStop() {
		unRegister();
		super.onStop();
	}

	/**
	 * 获取用户的 简称 名称
	 * 
	 * @return
	 */
	public String getNickRowName(String name) {
		if (TextUtils.isEmpty(name)) {
			return "";
		}
		if (name.length() <= 2) {
			return name;
		} else {
			return name.substring(name.length() - 2, name.length());
		}

	}

	@Override
	public void onRefreshBegin(PtrFrameLayout frame) {
		// TODO Auto-generated method stub

	}
}